const axios = require('axios')
const chalk = require("chalk");
const conf = new (require('conf'));

const api = new axios.create({
  baseURL: "http://127.0.0.1:7002/api/v1/"
})

api.interceptors.request.use(config => {
  if (conf.get('accessToken')) {
    config.headers['Authorization'] = 'Bearer ' + conf.get("accessToken");
  }

  return config;
})

api.interceptors.response.use((res) => {
  return res && res.data;
}, err => {
  if (err.response.status === 401) {
    console.log(chalk.redBright('no login'))
  }
  return err;
})

module.exports = class Base {
  constructor(name) {
    this.name = name;
    this.api = api;
  }

  async get(id) {
    return api.get(`${this.name}/${id}`);
  }

  async list(data = {}) {
    const params = Object.keys(data).reduce((acc, field) => {
      if (data[field]) {
        acc[field] = data[field];
      }
      return acc;
    }, {});
    return api.get(this.name, {params});
  }

  async insert(params) {
    return api.post(this.name, params);
  }

  async patch(id, params) {
    return api.patch(this.name + `/${id}`, params);
  }

  async delete(id) {
    return api.delete(this.name + `/${id}`);
  }
}
